import axios from 'axios';
import router from '@/router';
import qs from 'qs';
import merge from 'lodash/merge';
import { clearLoginInfo } from '@/utils';
import { Message, MessageBox } from 'element-ui';

// 判断消息提示框是否已经出现，防止重复弹出消息提示框
let isMessageVisible = false;

const http = axios.create({
  timeout: 1000 * 30,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json; charset=utf-8',
  },
});

function judgeToken() {
  const url = window.location.href;
  let data = qs.parse(url.split('?')[1]);
  if (sessionStorage.getItem('token') && !data.token) {
    return false;
  } else {
    if (data.token) {
      sessionStorage.setItem('token', data.token);
    }
  }
}
/**
 * 请求拦截
 */
http.interceptors.request.use(
  (config) => {
    judgeToken();
    config.headers['token'] = sessionStorage.getItem('token'); // 请求头带上token
    // config.headers['token'] = sessionStorage.getItem('token') // 请求头带上token
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

/**
 * 响应拦截
 */
http.interceptors.response.use(
  (response) => {
    // console.log("http response==>", response);
    if (response.data) {
      if (response.data.code === 401) {
        //异地登录
        if (isMessageVisible) {
          return response;
        }

        isMessageVisible = true;
        setTimeout(function () {
          MessageBox.alert(
            '检测到您的账号在别处登录，如非本人操作，建议您重新登录后尽快修改密码以确保账号安全！',
            '异地登录提示',
            {
              confirmButtonText: '确认',
              type: 'warning',
              callback: () => {
                isMessageVisible = false;
                clearLoginInfo();
                router.push({ name: 'login' });
              },
            }
          );
        }, 200);
      } else if (response.data.code === 501) {
        //平台授权过期
        if (isMessageVisible) {
          return response;
        }

        isMessageVisible = true;
        setTimeout(function () {
          MessageBox.alert(
            '当前平台授权已过期，请联系管理员对平台授权进行延期！',
            '平台授权过期提示',
            {
              confirmButtonText: '确认',
              type: 'warning',
              callback: () => {
                isMessageVisible = false;
                clearLoginInfo();
                router.push({ name: 'login' });
              },
            }
          );
        }, 200);
      } else if (
        response.data.code === 400 ||
        response.data.code === 402 ||
        response.data.code === 403 ||
        response.data.code === 499
      ) {
        //token失效
        if (isMessageVisible) {
          return response;
        }

        isMessageVisible = true;

        setTimeout(function () {
          isMessageVisible = false;
          Message({
            type: 'warning',
            message: response.data.msg,
          });
          clearLoginInfo();
          router.push({ name: 'login' });
        }, 200);
      }
    }

    return response;
  },
  (error) => {
    console.log('http response error', error);
    return Promise.reject(error);
  }
);

/**
 * 请求地址处理
 * @param {*} actionName action方法名称
 */
http.adornUrl = (actionName) => {
  // 非生产环境 && 开启代理, 接口前缀统一使用[/proxyApi/]前缀做代理拦截!
  return (
    (process.env.NODE_ENV !== 'production' && process.env.OPEN_PROXY
      ? '/proxyApi/'
      : window.SITE_CONFIG.baseUrl) + actionName
  );
};

/**
 * get请求参数处理
 * @param {*} params 参数对象
 * @param {*} openDefultParams 是否开启默认参数?
 */
http.adornParams = (params = {}, openDefultParams = true) => {
  var defaults = {
    t: new Date().getTime(),
  };
  return openDefultParams ? merge(defaults, params) : params;
};

/**
 * post请求数据处理
 * @param {*} data 数据对象
 * @param {*} openDefultdata 是否开启默认数据?
 * @param {*} contentType 数据格式
 *  json: 'application/json; charset=utf-8'
 *  form: 'application/x-www-form-urlencoded; charset=utf-8'
 */
http.adornData = (data = {}, openDefultdata = true, contentType = 'json') => {
  var defaults = {
    t: new Date().getTime(),
  };
  data = openDefultdata ? merge(defaults, data) : data;
  return contentType === 'json' ? JSON.stringify(data) : qs.stringify(data);
};

export default http;
